
import {useUserStore} from '@/stores/user'
import router from '@/router'
import axios from 'axios'

const baseURL = 'http://localhost:8080/api'

const instance = axios.create({
    baseURL,
    timeout:10000
})

instance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if(userStore.token){
            config.headers.Authorization = userStore.token
        }
        return config
    },
    (err) => PromiseRejectionEvent.reject(err)
)

instance.interceptors.response.use(
    (res) => {
        if(res.data.status === 200){
            return res
        }
        ElMessage.error(res.data.message || '服务器繁忙')
        return Promise.reject(res.data)
    },
    (err) => {
        if(err.response.status === 401) {
            router.push('/login')
        }
        ElMessage.error(err.response.data.message || '服务器繁忙')
        return Promise.reject(err)
    }
)

export default instance